<template>
  <div>
    <el-upload
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="onUpload"
      :action="upload.url"
      :with-credentials = "true"
      :disabled="disabled"
      class="avatar-uploader">
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"/>
    </el-upload>
  </div>
</template>

<script>
import { getAccountToken } from '@/utils/auth'
import { zBankCloudwalletUpload } from 'api/common'
import ImgCondense from '@/utils/imgCondense'

export default {
  name: 'Index',
  props: {
    value: {},
    disabled: {
      default: false,
      type: Boolean
    }
  },
  data() {
    return {
      upload: {
        headers: {
          accessToken: getAccountToken()
        },
        data: {
          'fileType': 'image',
          'info': '支付系统上传的图片文件'
        },
        url: process.env.BASE_API + '/account/common/zBankCloudwallet/upload'
      }
    }
  },
  methods: {
    //
    onUpload(data) {
      var ic = new ImgCondense(data.file)
      ic.imgPreview().then((fileData) => {
        console.log('fileData')
        console.log(fileData)
        var image = new FormData()
        image.append('file', fileData)
        image.append('info', '000')
        image.append('fileType', 'image')
        zBankCloudwalletUpload(image).then(response => {
          var imgPath = process.env.BASE_API + response.data.data.path
          console.log(imgPath)
          this.$emit('input', imgPath)
          this.$emit('change', response.data.data)
        })
      })
    },

    handleAvatarSuccess(res, file) {
      if (res.code != '0000') {
        this.$message.error(res.content)
      } else {
        var path = process.env.BASE_API + res.data.path
        this.$emit('input', path)
        this.$emit('change', res.data)
      }
    },
    beforeAvatarUpload(file) {
      var isJPG = false
      if (file.type === 'image/png' || file.type === 'image/jpeg') {
        isJPG = true
      }
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片格式需要是 JPG(jpg) 或者 PNG(png) 格式!')
      }
      // if (!isLt2M) {
      //   this.$message.error('上传图片大小不能超过 2MB!')
      // }
      // return isJPG && isLt2M
      return isJPG
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .avatar-uploader .el-upload {
    border: 1px dashed #868686;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
